// 运行时配置
import { RunTimeLayoutConfig, history } from '@umijs/max';
import { Modal, message, Avatar, Dropdown } from 'antd';
import { getUserInfo } from '@/services/userApi';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
export async function getInitialState(): Promise<{ currentUser?: API.UserInfo; loading?: boolean } | null> {
  try {
    if (window.localStorage.token) {
      const result = await getUserInfo();
      console.log("result--> ", result);
      return {
        currentUser: result,
        loading: false,
      };
    } else {
      return null;
    }
  } catch (error) {
    return {
      currentUser: undefined,
      loading: false,
    };
  }
}

/**
 * 配置 layout
 *
 * 参考链接：https://umijs.org/docs/max/layout-menu#%E8%BF%90%E8%A1%8C%E6%97%B6%E9%85%8D%E7%BD%AE
 * @returns
 */
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
    fixSiderbar: true,
    layout: 'mix',
    splitMenus: false,
    contentWidth: 'Fluid',
    colorPrimary: $PRIMARY,
    siderMenuType: 'sub',
    fixedHeader: true,
    siderWidth: 188,
    token: {
      sider: {
        colorMenuBackground: '#ffffff',
      },
      header: {
        colorBgHeader: '#001529',
        colorHeaderTitle: '#ffffff',
        heightLayoutHeader: 48,
      },
      pageContainer: {},
    },
    logout: () => {
      Modal.confirm({
        title: '注销登录',
        content: '确定要注销登录吗？',
        okText: '确定',
        cancelText: '取消',
        okButtonProps: {
          danger: true,
        },
        onOk: () => {
          window.localStorage.removeItem('token');
          history.replace('/login');
        },
      });
    },
    // 自定义右上角用户信息
    rightContentRender: () => {
      const { currentUser } = initialState || {};
      return (
        <Dropdown
          menu={{
            items: [
              {
                key: 'logout',
                label: '退出登录',
                onClick: () => {
                  Modal.confirm({
                    title: '注销登录',
                    content: '确定要注销登录吗？',
                    onOk: () => {
                      window.localStorage.removeItem('token');
                      history.replace('/login');
                    },
                  });
                },
              },
            ],
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
            <Avatar src={currentUser?.avator} size="small" />
            <span style={{ marginLeft: 8, color: '#fff' }}>{currentUser?.nickName || '未登录'}</span>
          </div>
        </Dropdown>
      );
    },
  };
};